package com.dyna.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLb implements LoadBalancer {

    private final AtomicInteger atomicInteger = new AtomicInteger(0);

//    写一个方法用来获取，请求次数
    public final int getAndIncrement(){
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        }while (!this.atomicInteger.compareAndSet(current,next));
        System.out.println("*****next:"+next);
        return next;
    }
    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
//        serviceInstances.size()服务器总数
//        getAndIncrement()调用这个方法，获取一个数，从1开始的，只是这个1是下标为0
        int index = getAndIncrement() % serviceInstances.size();
//        在这一步，获取到指定下标的实例，然后返了回去
        return serviceInstances.get(index);
    }
}
